package io.gitee.sfch.chunmi.springframework.argument;

import jakarta.annotation.Nonnull;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * 将String转换为{@link ICodeEnum}。使用{@link ICodeEnum#getCode()}进行equal比较
 *
 * @see ICodeEnum
 * @see CodeEnumArgumentNotValidException
 */
@Component
public class StringToCodeEnumConverterFactory implements ConverterFactory<String, ICodeEnum<?>> {

    @Nonnull
    @Override
    public <T extends ICodeEnum<?>> Converter<String, T> getConverter(@Nonnull Class<T> targetType) {
        return code -> {
            T[] enumConstants = targetType.getEnumConstants();
            for (T enumConstant : enumConstants) {
                if (enumConstant.getCode().toString().equals(code)) {
                    return enumConstant;
                }
            }
            return null;
        };
    }
}
